package mbms.mobilebudget;


import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.User;
import android.content.Intent;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;

public class RegistrationActivity extends OrmLiteBaseActivity<DatabaseHandler> {

	private EditText userName;
	private EditText email;
	private EditText lastname;
	private EditText firstname;
	private EditText pass;
	private EditText passAgain;
	private EditText secQuestion;
	private EditText secAnswer;
	
	private String s_userName;
	private String s_email;
	private String s_lastname;
	private String s_firstname;
	private String s_pass;
	private String s_passAgain;
	private String s_secQuestion;
	private String s_secAnswer;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registration);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.registration, menu);
		return true;
	}
	public void registerUser(View view) throws SQLException{
		
		userName= ((EditText) findViewById(R.id.editText1u));
		email= ((EditText) findViewById(R.id.rEmailAddress));
		lastname= ((EditText) findViewById(R.id.editText3));
		firstname= ((EditText) findViewById(R.id.editText4));
		pass= ((EditText) findViewById(R.id.editText5));
		passAgain= ((EditText) findViewById(R.id.editText6));
		secQuestion= ((EditText) findViewById(R.id.editText7));
		secAnswer= ((EditText) findViewById(R.id.editText8));
		
		s_userName= userName.getText().toString();
		s_email= email.getText().toString();
		s_lastname= lastname.getText().toString();
		s_firstname= firstname.getText().toString();
		s_pass= pass.getText().toString();
		s_passAgain= passAgain.getText().toString();
		s_secQuestion= secQuestion.getText().toString();
		s_secAnswer= secAnswer.getText().toString();

		int validation = validationCheck();
		
		if(validation > 0){
			if (validation == 2){
				Toast.makeText(getApplicationContext(), 
						"Passwords not matched.", Toast.LENGTH_SHORT).show();	
			}
			else{
				Toast.makeText(getApplicationContext(), 
						"All fields must be filled.", Toast.LENGTH_SHORT).show();	
			}
		    
		}
		else{
			User registerUser = new User();
		    registerUser.setUsername(s_userName);
		    registerUser.setPassword(s_pass);
		    registerUser.setCommEmailAddress(s_email);
		    registerUser.setFirstName(s_firstname);
		    registerUser.setLastName(s_lastname);
		    registerUser.setSequrityQuestion(s_secQuestion);
		    registerUser.setSequrityQuestionAnswer(s_secAnswer);

			String message = "";
			if(mandatoryCheckUser(registerUser, message)){
			
				try {
					Dao<User, Integer> userDao = getHelper().getUserDao();
					if(isEmailValid(registerUser.getCommEmailAddress())&&uniqueCheck(registerUser)){
						userDao.create(registerUser);	
						message= "User registered";
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();	
					}
					else{
						return;
					}
				
				} catch (SQLiteConstraintException e) {
					Toast.makeText(getApplicationContext(), 
							"Username is not unique", Toast.LENGTH_LONG).show();
					return;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}
			else {
				message = "Problem in registration";
				Toast.makeText(getApplicationContext(), 
						message, Toast.LENGTH_LONG).show();	
				return;
			}
			if(registerUser == null || !message.equals("")){
				if( message.equals("")){
					message = "Registration failed";
					Toast.makeText(getApplicationContext(), 
							message, Toast.LENGTH_LONG).show();	
					return;
				}
					
				else{
					Toast.makeText(getApplicationContext(), 
							message, Toast.LENGTH_LONG).show();	
				}
				
			}
			else{
				Dao<User, Integer> simpleDao = getHelper().getUserDao();
				
				User user1 = simpleDao.queryForId(registerUser.getId());
				message = "Registration for "+ user1.getUsername()+" successful";
				Toast.makeText(getApplicationContext(), 
						message, Toast.LENGTH_LONG).show();	
			}
				Intent intent = new Intent (this, MainActivity.class);
				startActivity(intent);
			}
		}
		
	public boolean uniqueCheck(User user){
		List<User> un ;
		try {
			Dao<User, Integer> userDao = getHelper().getUserDao();
			un = userDao.queryForEq("username", user.getUsername());
		}catch(SQLException e){
			Toast.makeText(getApplicationContext(), 
					"error while checking uniqueness", Toast.LENGTH_LONG).show();	
			return false;
		}
			if(un==null || un.isEmpty()){
				return true;
			}
			else{
				Toast.makeText(getApplicationContext(), 
						"Username is not unique", Toast.LENGTH_LONG).show();	
				return false;
			}
		
		
		
	}
	public void clearText(View view){
		((EditText) findViewById(R.id.editText1u)).setText("");
		((EditText) findViewById(R.id.rEmailAddress)).setText("");
		((EditText) findViewById(R.id.editText3)).setText("");
		 ((EditText) findViewById(R.id.editText4)).setText("");
		 ((EditText) findViewById(R.id.editText5)).setText("");
		 ((EditText) findViewById(R.id.editText6)).setText("");
		 ((EditText) findViewById(R.id.editText7)).setText("");
		((EditText) findViewById(R.id.editText8)).setText("");
	}
	public void redirectBack(View view){
		Intent intent = new Intent (this, MainActivity.class);
		startActivity(intent);
	}
	private int validationCheck(){
		if(s_userName.equals("") || s_email.equals("") || s_firstname.equals("") || s_pass.equals("") || s_lastname.equals("") 
				|| s_passAgain.equals("") || s_secQuestion.equals("") || s_secAnswer.equals("") ){
			return 1;
		}
		else if ( !s_pass.equals(s_passAgain)){
			return 2;
		}
		else
			return 0 ;
	}
	private boolean mandatoryCheckUser(User user, String msg){
		if(user == null || user.getCommEmailAddress().equals("")| user.getFirstName().equals("") || user.getLastName().equals("") || 
				user.getPassword().equals("") || user.getSequrityQuestion().equals("")  ||
				user.getSequrityQuestionAnswer().equals("")|| user.getUsername().equals("")){
			msg = "All fields must be filled";
			return false;
		}
		else
			return true;
	}
	public boolean isEmailValid(String email)
    {
         String regExpn =
             "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                 +"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                   +"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                   +"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

     CharSequence inputStr = email;

     Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(inputStr);

     if(matcher.matches()){
    	 return true;	
     }
        
     else{
    	 Toast.makeText(getApplicationContext(), 
					"Email is not valid", Toast.LENGTH_LONG).show();	
    	 return false;
     }
        
}
}
